package com.course.server.service;

import cn.hutool.core.util.StrUtil;
import com.course.server.domain.Chapter;
import com.course.server.domain.ChapterExample;
import com.course.server.dto.ChapterDto;
import com.course.server.dto.PageDto;
import com.course.server.mapper.ChapterMapper;
import com.course.util.CopyUtil;
import com.course.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author 12392
 */
@Service
public class ChapterService {


    @Autowired
    private ChapterMapper chapterMapper;


    public void list(PageDto<ChapterDto> pageDto) {
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());
        ChapterExample example = new ChapterExample();
        List<Chapter> chapterList = chapterMapper.selectByExample(example);
        PageInfo<Chapter> pageInfo = new PageInfo<>(chapterList);
        pageDto.setTotal(pageInfo.getTotal());
        List<ChapterDto> chapterDtos = CopyUtil.copyList(chapterList, ChapterDto.class);
        pageDto.setList(chapterDtos);
    }

    /**
     * 保存 / 更新
     *
     * @param chapterDto 章
     */
    public void saveOrUpdate(ChapterDto chapterDto) {
        Chapter chapter = CopyUtil.copy(chapterDto, Chapter.class);
        if (StrUtil.isBlank(chapterDto.getId())) {
            insert(chapter);
        } else {
            update(chapter);
        }
    }

    protected void insert(Chapter chapter) {
        chapter.setId(UuidUtil.getShortUuid());
        chapterMapper.insert(chapter);
    }

    protected void update(Chapter chapter) {
        chapterMapper.updateByPrimaryKey(chapter);
    }

    public void deleteById(String id) {
        int i = chapterMapper.deleteByPrimaryKey(id);
    }
}
